import 'package:ichinesereader/constants.dart';

class JavaScriptCalls {
  static String jsSetIframeWindow =
      "var script = document.createElement('script'); script.type = 'text/javascript';script.text = \"var frm = \$('#content-frame')[0].contentWindow; \"; document.getElementsByTagName('head')[0].appendChild(script);";
  static String jsMusicOn = "frm.bgmOn()";
  static String jsMusicOff = "frm.bgmOff()";
  static String jsShowPinyin = "frm.showPinyin()";
  static String jsHidePinyin = "frm.hidePinyin()";
  static String jsAudioOn = "frm.readOn()";
  static String jsAudioOff = "frm.readOff()";
  static String jsGotoFirstPage = "frm.goFirstPage()";
  static String jsGotoLastPage = "frm.goLastPage()";
  static String jsGetPage = "frm.getPage()";
  static String jsGetTotalPages = "frm.getTotalPage()";
  static String jsUpdatePage =
      "var script = document.createElement('script'); script.type = 'text/javascript';script.text = \"function updatePage(page, total) { Current_Page = page; Book_Total_Pages = total; console.log('totalpages from flutter:' \$pageNum['total']);}\"; document.getElementsByTagName('head')[0].appendChild(script);";
  static String jsShowSimpleText = "frm.showText('s')";
  static String jsShowTraditionalText = "frm.showText('t')";
  static String jsShowMandarinText = "frm.fLangToggle('m')";
  static String jsShowCantoneseText = "frm.fLangToggle('c')";
  static String jsHideText = "frm.hideText()";
  static String jsPauseRead = "frm.pauseRead()";
  static String jsResumeRead = "frm.resumeRead()";
  static String jsAutoplayOn = "frm.autoplayOn()";
  static String jsAutoplayOff = "frm.autoplayOff()";
  static String srcEvaluation(
      _lang, _language, _bookCode, _userName, _authtoken) {
    return """// url for test
              // var preURLSuper = "https://superbe.migration.ichinesereader.com";
                var preURLSuper = '${Constants.BaseAPISuper}';

                // for upload recording
                var preURL = '${Constants.BaseAPI}';

                const admin = 'superadmin';

                function getAuthToken(value) {
                    var token = localStorage.getItem('authToken');
                    return token || value;
                }
                function getBookId() {
                    var bookId = localStorage.getItem('bookID');
                    return bookId || (window.bookInstance && window.bookInstance.id);
                }
                function getBookCode(value) {
                    var bookCode = localStorage.getItem('bookCode');
                    return bookCode || value;
                }
                function getLanguage(value) {
                    var language = localStorage.getItem('siteLang');
                    return language || value;
                }
                function getBilingualLanguage(value) {
                    var bilingualLanguage = localStorage.getItem('lang');
                    return bilingualLanguage || value;
                }
                function getWordMode(value) {
                    var lang = localStorage.getItem('language');
                    return lang || value;
                }
                function getUserName(value) {
                    var userName = localStorage.getItem('userName');
                    return userName || value;
                }
                // function to get word lists for each book
                // bookCode:string from localStorage bookCode, AuthToken:string from localStorage AuthToken, language:string from localStorage siteLang, wordMode:string from localStorage language, bilingualLanguage :string from localStorage lang
                // to test in book editer, you can test with some static data
                // language: Simplified,(Korean will be considered later..)
                function getBookWordList(bookCode, authToken, language, wordMode, bilingualLanguage){
                    var defer = jQuery.Deferred();
                    jQuery.ajax({
                        type: "GET",
                        url:  preURLSuper + admin + '/knowledge/word/book/' + getBookCode(bookCode),
                        data: { 
                            language: 'English', 
                            // simplified: getWordMode(wordMode) === 'Simplified', 
                            // mandarin: getBilingualLanguage(bilingualLanguage) === 'Mandarin',
                            simplified: getWordMode(wordMode), 
                            mandarin: getBilingualLanguage(bilingualLanguage),
                        },
                        beforeSend: function (request) {
                            if (authToken) {
                                request.setRequestHeader("AuthToken", getAuthToken(authToken));
                            }
                        },
                        contentType: 'application/json',
                        success: function(response){
                            //console.log(response);
                            defer.resolve(response);
                        }
                    });
                    return defer.promise();
                }
                // for AI audio test
                // parse the audio file
                // authToken: from localStorage AuthToken
                function AudioTest(file, authToken){
                    var fd = new FormData();
                    fd.append('file', file);

                    var defer = jQuery.Deferred();
                    jQuery.ajax({
                        type: "POST",
                        url: preURLSuper + admin + '/speech/recognition',
                        beforeSend: function (request) {
                            if (authToken) {
                                request.setRequestHeader("AuthToken", getAuthToken(authToken));
                            }
                        },
                        data: fd,
                        processData: false,
                        contentType: false,
                        success: function(response){
                            defer.resolve(response);
                        }
                    });
                    return defer.promise();
                }

                // this function is called when want to save the recording
                // questions: Json object. the anwser in each qustion should be the following format 
                //           (['answer1'], or ['answer1', 'answer2'...], or ['match1|answer1', 'match2|answer2'...])
                // bilingualLanguage: Mandarin or Cantonese from localStorage lang
                // wordMode: Simplified or Traditional from localStorage language
                // userName: string from localStorage userName
                // authToken: from localStorage AuthToken
                // bookCode: from localStorage bookCode

                function createQuestionRecord(questions, bilingualLanguage, wordMode, userName, bookCode, authToken){
                    var defer = jQuery.Deferred();

                    let questionRecordForm = {
                        "assessmentId": "",
                        "audioType": getBilingualLanguage(bilingualLanguage),
                        "bookCode": getBookCode(bookCode),
                        "kind": "CUSTOMIZE",
                        "mode": "Exercise",
                        "questionGroupId": null,
                        "record": questions,
                        "textType": getWordMode(wordMode),
                        "type": "CUSTOMIZE",
                        "userName": getUserName(userName)
                    }
                    jQuery.ajax({
                        type: "POST",
                        url:  preURLSuper + admin + "/question/record",
                        data: JSON.stringify(questionRecordForm),
                        beforeSend: function (request) {
                            if (authToken) {
                                request.setRequestHeader("AuthToken", getAuthToken(authToken));
                            }
                        },
                        contentType: 'application/json',
                        success: function(response){
                            //console.log(response);
                            defer.resolve(response);
                        }
                    });
                    return defer.promise();
                }
                // this function is use to submit the evaluation and will be called when complete the pyp series book's anwsers
                // questions: Json object. the anwser in each qustion should be the following format (['answer1'], or ['answer1', 'answer2'])
                // bilingualLanguage: Mandarin or Cantonese from localStorage lang
                // wordMode: Simplified or Traditional from localStorage language
                // userName: string from localStorage userName
                // authToken: from localStorage AuthToken
                // bookCode: from localStorage bookCode

                function assessmentEvaltest(questions, bilingualLanguage, wordMode, userName, bookCode, authToken){
                    var defer = jQuery.Deferred();
                    // otherwise there is error wehn calling assessmentEvaltest finction
                    var _lang = _lang;
                    if (_lang == "No_audio") {
                      _lang = "Mandarin";
                    }
                    var questionRecordForm = {
                        "audioType": _lang,
                        "bookCode": _bookCode,
                        "kind": "CUSTOMIZE",
                        "mode": "Exercise",
                        "questionGroupId": null,
                        "record": questions,
                        "textType": _language,
                        "type": "CUSTOMIZE",
                        "userName": _userName
                    }
                    jQuery.ajax({
                        type: "POST",
                        url:  preURLSuper + admin + "/question/assessment/test",
                        data: JSON.stringify(questionRecordForm),
                        beforeSend: function (request) {
                            if (authToken) {
                              request.setRequestHeader("AuthToken", _authtoken);
                            }
                        },
                        contentType: 'application/json',
                        success: function(response){
                            console.log(response);
                            defer.resolve(response);
                        },
                        error: function (xhr, ajaxOptions, thrownError) {
                          alert(xhr.status);
                        }
                        
                    });
                }

                // called when save the words to server
                // authToken: from localStorage AuthToken
                function saveWord(wordId, authToken){  
                    var defer = jQuery.Deferred();
                    jQuery.ajax({
                        type: "POST",
                        url: preURLSuper + admin + '/knowledge/word/save/' + wordId,
                        async: false,
                        beforeSend: function (request) {
                            if (authToken) {
                                request.setRequestHeader("AuthToken", getAuthToken(authToken));
                            }
                        },
                        success: function(response){
                            // console.log(response);
                            defer.resolve(response);
                        }
                    });
                    return defer.promise();
                }

                // Save recording file and return recording address fileId 
                // authToken: from localStorage AuthToken
                function uplodeRecordFileInBook(fd, authToken){
                    var defer = jQuery.Deferred();
                    jQuery.ajax({
                        type: "POST",
                        url: preURL + '/studentmanager/file',
                        beforeSend: function (request) {
                            if (authToken) {
                                request.setRequestHeader("AuthToken", getAuthToken(authToken));
                            }
                        },
                        data: fd,
                        processData: false,
                        contentType: false,
                        success: function(response){
                            defer.resolve(response);
                        }
                    });
                    return defer.promise();
                }""";
  }
}
